const path = require('path');
const { execSync } = require('child_process');
const {readFile, writeTextToFile, copyFileAsync, replaceAll} =require('./tools.js')

build()

async function build () {
    // 读取package.json文件
    const packageJson = readFile(path.resolve(__dirname, '../../package.json'))
    const version = JSON.parse(packageJson).version

    // 完成组件编译
    try {
        const output = execSync('npm run package', { encoding: 'utf8' , cwd:process.cwd()});
        console.log(`输出:\n${output}`);
    } catch (error) {
        console.error(`执行错误: ${error}`);
    }

    // 拷贝package到编译目录
    const sourcePath = path.resolve(__dirname, './package-template.json');
    const targetPath = path.resolve(process.cwd(), `./beline-ui/package.json`);
    await copyFileAsync(sourcePath, targetPath)
        .then(() => {
            console.log(`文件复制成功: ${sourcePath} -> ${targetPath}`);
        })
        .catch((error) => {
            console.error('文件复制失败:', error);
        });

      // 处理beline-ui文件夹下的package.json
    const belineUIPackageJson = readFile(path.resolve(process.cwd(), './beline-ui/package.json'))
    const newBelineUIPackageJson = replaceAll(belineUIPackageJson, '<%version%>', version)
    // 把处理完的package.json写回
    writeTextToFile( newBelineUIPackageJson, path.resolve(process.cwd(), './beline-ui/package.json'))
    .then(() => {
        console.log(`文件写入成功: ${path.resolve(process.cwd(), './beline-ui/package.json')}`);
    })
    .catch((error) => {
        console.error('文件写入失败:', error);
    });
}
